package com.gking.centerSystem.service.Permissions;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gking.centerSystem.common.BaseContext;
import com.gking.centerSystem.common.ProgramException;
import com.gking.centerSystem.common.Result;
import com.gking.centerSystem.entity.Permissions;
import com.gking.centerSystem.entity.Sort;
import com.gking.centerSystem.mapper.PermissionsMapper;
import com.gking.centerSystem.service.Sort.SortService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PermissionsServiceImpl extends ServiceImpl<PermissionsMapper, Permissions> implements PermissionsService {

    @Resource
    private SortService sortService;

    @Resource
    private PermissionsMapper permissionsMapper;

    /**
     * 通过一个分类id找出该分类下的所有分类id
     *
     * @param id 分类id
     * @return s
     */
    private List<String> getIds(String id) {
        List<String> idList = new ArrayList<>();
        idList.add(id);

        // 将分类下的所有权限分类id查找出来
        LambdaQueryWrapper<Sort> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Sort::getParentId, id);
        queryWrapper.eq(Sort::getIsDelete, 0);
        queryWrapper.eq(Sort::getType, "permission");
        List<Sort> sorts = sortService.list(queryWrapper);

        // 递归找出所有id
        for (Sort sort : sorts) idList.addAll(getIds(sort.getId()));
        return idList;
    }

    /**
     * 获取权限列表
     *
     * @param sortId 分类id
     * @param size   分页大小
     * @param page   分页页码
     * @return s
     */
    @Override
    public Result<Page> getPermissionsList(String sortId, Integer size, Integer page) {

        if (Objects.equals(sortId, "")) sortId = null;
        if (size == null || page == null) return Result.error("分页参数不能为空！");

        try {
            List<String> ids = new ArrayList<>();
            if (sortId != null) { //是否为条件查询
                ids = new ArrayList<>(new HashSet<>(getIds(sortId)));
            }

            Page<Permissions> pageInfo = new Page<>(page, size);
            Page<Permissions> pageResult = permissionsMapper.getPermissionsList(pageInfo, ids);

            return Result.success("获取权限列表成功！", pageResult);
        } catch (Exception e) {
            log.error("获取权限列表失败！ {} ", e.getMessage());
            throw new ProgramException();
        }
    }

    /**
     * 创建权限或者修改权限信息
     *
     * @param name         权限名称
     * @param code         权限信息
     * @param description  描述
     * @param sortId       分类id
     * @param permissionId 权限id
     * @return s
     */
    @Override
    public Result<String> setPermission(String name, String code, String description, String sortId, String permissionId) {

        if (name.isEmpty() || code.isEmpty() || description.isEmpty() || sortId.isEmpty())
            return Result.error("请将参数补充完整");
        if (Objects.equals(permissionId, "")) permissionId = null;

        try {
            Sort s = sortService.getById(sortId);
            if (s == null) return Result.error("分类不存在！");
            if (!Objects.equals(s.getType(), "permission")) return Result.error("该分类不是权限分类！");


            Permissions permissions = new Permissions();
            permissions.setName(name);
            permissions.setCode(code);
            permissions.setDescription(description);
            permissions.setSortId(sortId);
            permissions.setUpdateTime(LocalDateTime.now());
            permissions.setUpdateUserId(BaseContext.getCurrentId());
            permissions.setSystemCode(s.getSystemCode());

            //权限id不存在则创建
            if (permissionId == null) {
                permissions.setCreateUserId(BaseContext.getCurrentId());
                this.save(permissions);
                return Result.success("创建权限成功！");
            }
            //权限id存在则更新
            permissions.setId(permissionId);
            this.updateById(permissions);
            return Result.success("修改权限成功！");
        } catch (Exception e) {
            log.error("创建权限失败！ {} ", e.getMessage());
            throw new ProgramException();
        }
    }

    /**
     * 批量删除权限
     *
     * @param permissionIdList 权限id列表
     * @return s
     */
    @Transactional
    @Override
    public Result<String> deletePermissions(List<String> permissionIdList) {
        try {
            if (permissionIdList.isEmpty()) return Result.error("请选择要删除的权限");

            LambdaUpdateWrapper<Permissions> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(Permissions::getIsDelete, 1);
            updateWrapper.set(Permissions::getDeleteUserId, BaseContext.getCurrentId());
            updateWrapper.set(Permissions::getDeleteTime, LocalDateTime.now());
            updateWrapper.in(Permissions::getId, permissionIdList);
            this.update(updateWrapper);

            return Result.success("删除权限成功！");
        } catch (Exception e) {
            log.error("删除权限失败！ {} ", e.getMessage());
            throw new ProgramException();
        }
    }

    /**
     * 批量更新权限状态
     *
     * @param permissionIdList 权限id 列表
     * @param status           状态 0启用，1禁用
     * @return s
     */
    @Transactional
    @Override
    public Result<String> updatePermissionsStatus(List<String> permissionIdList, Integer status) {
        try {
            if (permissionIdList.isEmpty() || status == null) return Result.error("请将参数补充完整");
            if (status < 0 || status > 1) return Result.error("状态参数错误");

            LambdaUpdateWrapper<Permissions> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(Permissions::getEnable, status);
            updateWrapper.set(Permissions::getUpdateUserId, BaseContext.getCurrentId());
            updateWrapper.set(Permissions::getUpdateTime, LocalDateTime.now());
            updateWrapper.in(Permissions::getId, permissionIdList);
            this.update(updateWrapper);

            return Result.success("更新权限状态成功！");
        } catch (Exception e) {
            log.error("更新权限状态失败！ {} ", e.getMessage());
            throw new ProgramException();
        }
    }

}
